<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { onBeforeMount, reactive, ref } from 'vue'
import apiToDo from "@/api/modules/todo"
import useUserStore from "@/store/modules/user"//从store获取用户
import useTodoStore from "@/store/modules/todo"

function useFormDialog() {
  const dialogVisible = ref(false)
  const mode = ref<'create' | 'edit'>('create')
  const formModal = reactive<ToDoApiTypes>({
    id: 0,
    user_id: -1,
    todo: '',
    finish: 0,
    DDL: ''
  })
  const open = () => {
    dialogVisible.value = true
  }

  const setMode = (type: 'create' | 'edit') => {
    mode.value = type
  }
  const setForm = (source: ToDoApiTypes) => {
    formModal.id = source.id
    formModal.user_id = source.user_id
    formModal.todo = source.todo
    formModal.finish = source.finish
    formModal.DDL = source.DDL
  }
  const clearForm = () => {
    formModal.id = 0
    formModal.user_id = -1
    formModal.todo = ''
    formModal.finish = 0
    formModal.DDL = ''
  }

  const close = () => {
    dialogVisible.value = false
  }

  return {
    dialogVisible,
    mode,
    open,
    close,
    setMode,
    formModal,
    setForm,
    clearForm,
  }
}

const { open, close, setMode, dialogVisible, mode, formModal, setForm, clearForm } = useFormDialog()

function editTodo(row: ToDoApiTypes) {
  setForm(cloneDeep(row))
  setMode('edit')
  open()
}

function createTodo() {
  clearForm()
  setMode('create')
  open()
}

// 获取待办列表
const paginator = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const data = ref<ToDoApiTypes[]>([])
const loading = ref(true)
function loadTodos() {
  loading.value = true;
  apiToDo.getList({
    page: paginator.page,
    pageSize: paginator.pageSize,
    userId: useUserStore().id as number // 添加当前用户ID
  }).then((res) => {
    data.value = res.data.list;
    paginator.total = res.data.total;
    //将data第一条数据存入全局变量 异步
    useTodoStore().addTodo(data.value[0])
  }).finally(() => {
    loading.value = false;
  });



}

onBeforeMount(() => {
  loadTodos()
})

// 创建/编辑待办事件
function onCommitForm() {
  if (formModal.todo === '') {
    ElMessage({
      type: 'error',
      message: '待办内容不能为空',
    })
    return
  }
  if (formModal.DDL === '') {
    ElMessage({
      type: 'error',
      message: '截止时间不能为空',
    })
    return
  }
  close()
  loading.value = true
  const apiPromise = mode.value === 'create'
    ? apiToDo.add({
      id:formModal.id,
      user_id: Number(useUserStore().id),//从useUserStore获取id
      todo: formModal.todo,
      finish: formModal.finish,
      DDL: formModal.DDL,
    })
    : apiToDo.editTodo({
      id:formModal.id,
      user_id: Number(useUserStore().id),//从useUserStore获取id
      todo: formModal.todo,
      finish: formModal.finish,
      DDL: formModal.DDL,
    })
  apiPromise.then(() => {
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
  }).finally(() => {
    loadTodos()
  })
}

// 删除待办事件
function deleteTodo(id: number) {
  loading.value = true
  apiToDo.deleteTodo(id).then(() => {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  }).finally(() => {
    loadTodos()
  })
}

// 状态文本映射
const statusMap: Record<TodoStatus, string> = {
  0: '待做',
  1: '完成'
};
</script>

<template>
  <div>
    <PageMain v-loading="loading">
      <el-button type="primary" @click="createTodo">
        添加待办
      </el-button>
      <el-table :data="data" stripe>
        <el-table-column type="index" width="50" />
        <el-table-column prop="todo" label="待办内容" />
        <el-table-column prop="ddl" label="截止时间" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.finish === 0 ? 'info' : 'warning'">
              {{ statusMap[row.finish]}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="editTodo(row)">
              编辑
            </el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              confirm-button-type="danger"
              icon-color="#F56C6C"
              title="是否删除该待办事项"
              @confirm="deleteTodo(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          v-model:current-page="paginator.page"
          v-model:page-size="paginator.pageSize"
          layout="sizes, prev, pager, next"
          :total="paginator.total"
          :page-sizes="[5, 10, 20, 50]"
          background
          @current-change="loadTodos()"
          @size-change="loadTodos()"
        />
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="mode === 'create' ? '添加待办' : '编辑待办'"
        width="100%" style="max-width: 600px;"
      >
        <el-form :model="formModal" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="待办内容">
                <el-input v-model="formModal.todo" placeholder="请输入待办内容" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-select v-model="formModal.finish" placeholder="请选择状态">
                  <el-option label="未开始" :value="0" />
                  <el-option label="完成" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止时间">
                <el-date-picker
                  v-model="formModal.DDL"
                  type="datetime"
                  placeholder="选择截止时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="onCommitForm">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </PageMain>
  </div>
</template>

<style lang="scss" scoped>
.page {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>

